package io.persimmon.core.module.trace;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Data
@Slf4j
public class TraceContext {

    private int id;
    private String name;
    private List<TraceInfo> traceInfoList;

    public TraceContext(String name) {
        this.name = name;
        this.id = (System.currentTimeMillis() + this.name).hashCode();
        this.traceInfoList = new ArrayList<>();
    }

    public void addTraceInfo(TraceInfo traceInfo) {
        this.traceInfoList.add(traceInfo);
    }

    public void printLog() {
        String trace = this.name + ":" + this.id;
        traceInfoList.forEach(traceInfo -> doPrintLog(trace, traceInfo));
    }

    private void doPrintLog(String trace, TraceInfo traceInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String dateTime = sdf.format(traceInfo.getTime());
        Logger actualLogger = Optional.ofNullable(traceInfo.getLogger()).orElse(log);

        if (Objects.nonNull(traceInfo.getData()) && traceInfo.getData() instanceof Object[]) {
            actualLogger.info("{} trace log: " + dateTime + " " + traceInfo.getMsg(), trace, (Object[]) traceInfo.getData());
        } else {
            actualLogger.info("{} trace log:  " + dateTime + " " + traceInfo.getMsg(), trace, traceInfo.getData());
        }
    }
}
